package hgin

import (
	"encoding/json"
	"errors"
	"github.com/gin-gonic/gin"
)

// MiddlewareError gin.Context错误处理中间件
func MiddlewareError(ctx *gin.Context) {
	defer func() {
		if e := recover(); e != nil {
			switch e.(type) {
			case error:
				_ = ctx.Error(e.(error))
			default:
				b, _ := json.Marshal(e)
				_ = ctx.Error(errors.New(string(b)))
			}

		}
		if len(ctx.Errors) > 0 {
			ApiRes(ctx, ctx.Errors.Last())
		}
	}()
	ctx.Next()
}
